package cn.ynu.cmrs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;

import cn.ynu.cmrs.R;
import cn.ynu.cmrs.AppConstant;
import cn.ynu.cmrs.MyApplication;
import cn.ynu.cmrs.adapter.CommentAdapter;
import cn.ynu.cmrs.asyncTask.GetInfosTask;
import cn.ynu.cmrs.model.Comment;
import cn.ynu.cmrs.model.CommentItem;
import cn.ynu.cmrs.utils.JsonParse;
import cn.ynu.cmrs.utils.WebInterface;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.Toast;
import android.widget.ListView;
import android.widget.ViewFlipper;

/**
 * Activity representing comments
 * 
 * @author Yasha
 * 
 */
public class CommentActivity extends Activity implements OnItemClickListener,
		OnClickListener {

	private static final int COMMENT = 0;
	private static final int RETURN_HOME = 1;
	private static final int RETURN = 3;
	private ListView listView;
	private ImageButton commentButton;
	private ImageButton returnHomeButton;
	private ImageButton returnButton;
	private View process;
	private String courseID;
	/**
	 * The pages had displayed
	 */
	private int nowpage = 1;
	/**
	 * The amount of total comments
	 */
	private int totalItemsCount = 0;
	/**
	 * The amount of comment had got
	 */
	private int existingItemsCount = 0;
	/**
	 * Flag indicates whether the user had click to "See more"
	 */
	private boolean getMoreFlag;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.i("CommentActivity", " ---> onCreate");
		MyApplication.allActivity.add(this);
		setContentView(R.layout.comment);
		Intent intent = getIntent();
		// Get course ID from the Intent
		courseID = intent.getStringExtra("courseID");
		prepareView();
		setListener();
		new GetCommentsTask(this, R.string.fail_general, process).execute();
	}

	/**
	 * Add listeners for controls
	 */
	private void setListener() {
		commentButton.setTag(COMMENT);
		returnHomeButton.setTag(RETURN_HOME);
		returnButton.setTag(RETURN);
		commentButton.setOnClickListener(this);
		returnHomeButton.setOnClickListener(this);
		returnButton.setOnClickListener(this);
		listView.setOnItemClickListener(this);
	}

	/**
	 * Prepare views which will be used
	 */
	private void prepareView() {
		listView = (ListView) findViewById(R.id.comments_listview);
		process = findViewById(R.id.progress_commentlist);
		commentButton = (ImageButton) findViewById(R.id.comment_button);
		returnButton = (ImageButton) findViewById(R.id.return_btn);
		returnHomeButton = (ImageButton) findViewById(R.id.return_home_btn);
	}

	/**
	 * AsyncTask class, get comments from server
	 * 
	 * @author Yasha
	 * 
	 */
	private class GetCommentsTask extends GetInfosTask<Void, Comment> {

		public GetCommentsTask(Activity mActivity, int mFailMsg, View mView) {
			super(mActivity, mFailMsg, mView);
			// TODO Auto-generated constructor stub
		}

		@Override
		protected Comment doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "getcomment");
			param.put("courseid", courseID);
			param.put(
					"start",
					String.valueOf((nowpage - 1)
							* AppConstant.MostUsedConstant.pageSize + 1));
			param.put("amount",
					String.valueOf(AppConstant.MostUsedConstant.pageSize));
			String result = WebInterface.webInterface(param);
			Comment comments;
			try {
				comments = JsonParse.getComment(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				comments = new Comment(null, null, new String[] { "8086",
						mActivity.getString(R.string.inner_error_json) });
			}

			return comments;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub

		}

		@Override
		protected void onPostExecute(Comment result) {
			// TODO Auto-generated method stub
			String[] status = result.getStatus();
			if (status[0].equals("0")) {
				doStuffWithResult(result);
			} else {
				failMsg(status[1]);
			}
			getMoreFlag = false;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			if (nowpage == 1) {
				mView.setVisibility(View.VISIBLE);
			}
		}

		@Override
		protected void onProgressUpdate(View... values) {
			// TODO Auto-generated method stub

		}

		@Override
		protected void doStuffWithResult(Comment result) {
			// TODO Auto-generated method stub
			ViewFlipper viewFlipper = (ViewFlipper) findViewById(R.id.comment_content);
			List<CommentItem> commentItems = result.getItems();
			if (nowpage == 1) {
				mView.setVisibility(View.GONE);
				if (commentItems != null && commentItems.size() > 0) {
					viewFlipper.setDisplayedChild(0);
					totalItemsCount = commentItems.size();
					existingItemsCount = commentItems.size();
					CommentAdapter myCommentAdapter = new CommentAdapter(
							mActivity,
							new ArrayList<CommentItem>(commentItems), listView);
					listView.setAdapter(myCommentAdapter);
					nowpage++;
				} else {
					viewFlipper.setDisplayedChild(1);
				}
			} else {
				if (commentItems != null && commentItems.size() > 0) {
					existingItemsCount += commentItems.size();
					((CommentAdapter) listView.getAdapter())
							.addMoreData(new ArrayList<CommentItem>(
									commentItems));
					nowpage++;
				}
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		if (arg3 == -1) { // clicked "see more"
			if (!getMoreFlag) {
				if (existingItemsCount >= totalItemsCount) { // All items has
																// displayed
					Toast.makeText(CommentActivity.this, R.string.no_moreitems,
							Toast.LENGTH_SHORT).show();
				} else { // Load more comments
					getMoreFlag = true;
					new GetCommentsTask(CommentActivity.this,
							R.string.fail_general, process).execute();
				}
			} else {

			}
		}
	}

	/**
	 * AsyncTask class, to submit a comment to the server
	 * 
	 * @author Yasha
	 * 
	 */
	private class PostCommentTask extends AsyncTask<String, Void, String[]> {

		private Activity mContext;
		private int mSuccessMsg;
		//private int mFailMsg;

		public PostCommentTask(Activity mContext, int mSuccessMsg, int mFailMsg) {
			super();
			this.mContext = mContext;
			this.mSuccessMsg = mSuccessMsg;
			//this.mFailMsg = mFailMsg;
		}

		@Override
		protected String[] doInBackground(String... params) {
			// TODO Auto-generated method stub
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "postcomment");
			param.put("userid", MyApplication.nowUser.getId());
			param.put("courseid", params[0]);
			param.put("comment", params[1]);
			param.put("mark", params[2]);
			String result = WebInterface.webInterface(param);
			String[] status;
			try {
				status = JsonParse.getStatus(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				status = new String[] { "8086",
						mContext.getString(R.string.inner_error_json) };
			}
			return status;
		}

		@Override
		protected void onPostExecute(String[] result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			if (result[0].equals("0")) {
				Toast.makeText(mContext, getString(mSuccessMsg),
						Toast.LENGTH_LONG).show();
				nowpage = 1;
				new GetCommentsTask(CommentActivity.this,
						R.string.fail_general, process).execute();
			} else {
				Toast.makeText(mContext, result[1], Toast.LENGTH_LONG).show();
			}
		}
	}

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param context
	 *            context from which Activity should be started
	 */
	public static void launch(Context context) {
		Intent intent = new Intent(context, CommentActivity.class);
		context.startActivity(intent);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		MyApplication.allActivity.remove(this);
		this.finish();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int tag = (Integer) v.getTag();
		switch (tag) {
		case RETURN: // Return to previous Activity
			this.finish();
			break;
		case RETURN_HOME: // Return to MainActivity
			this.finish();
			MyApplication.getActivityByName("CourseDetailActivity").finish();
			break;
		case COMMENT: // Show a dialog to get comment content
			LayoutInflater factory = LayoutInflater.from(CommentActivity.this);
			View comment = factory.inflate(R.layout.comment_it, null);
			final EditText etContent = (EditText) comment
					.findViewById(R.id.etCommentContent);
			final RatingBar mMark = (RatingBar) comment
					.findViewById(R.id.mark_comment);
			new AlertDialog.Builder(CommentActivity.this)
					.setTitle(R.string.comment)
					.setView(comment)
					.setPositiveButton(R.string.strComment,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO Auto-generated method stub
									String errorMsg = "";
									String content = etContent.getText()
											.toString();
									float mark = mMark.getRating();
									if (content.equals("")) {
										errorMsg = getString(R.string.fail_general)
												+ getString(R.string.error_content_null);
									}
									if (errorMsg.equals("")) {
										new PostCommentTask(
												CommentActivity.this,
												R.string.post_comment_success,
												R.string.fail_general).execute(
												courseID, content, mark * 2
														+ "");
									} else {
										Toast.makeText(CommentActivity.this,
												errorMsg, Toast.LENGTH_LONG)
												.show();
									}
								}
							}).setNegativeButton(R.string.cancel, null).show();
			break;
		default:
			break;
		}
	}
}
